package com.xaicode.auth.security.scope;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.Objects;
import java.util.Optional;

/**
 * 辅助数据权限实现 threadLocal 存储追加 sql
 * 
 * @date 2024/12/6
 */
public class DataScopeContextHelper {

    /**
     * 缓存数据权限的 sql 片段
     */
    private static final TransmittableThreadLocal<String> LOCAL_DATA_SCOPE_SQL = new TransmittableThreadLocal<>();

    /**
     * 是否开启数据权限
     */
    private static final TransmittableThreadLocal<Boolean> ENABLED = new TransmittableThreadLocal<>();

    public static void enabled(boolean enable) {
        ENABLED.set(enable);
    }

    public static void set(String sql) {
        LOCAL_DATA_SCOPE_SQL.set(sql);
    }

    public static String get() {
        if (Objects.nonNull(ENABLED.get()) && ENABLED.get()) {
            return Optional.ofNullable(LOCAL_DATA_SCOPE_SQL.get()).orElse("");
        }
        return "";
    }

    public static void clear() {
        LOCAL_DATA_SCOPE_SQL.remove();
        ENABLED.remove();
    }

}
